import BaseCURDApi from '@/framework/infra/base/BaseCURDApi'
import {roleApi} from "@/feature/mgr/infra/api/roleApi";

class PermissionApi extends BaseCURDApi {
  constructor() {
    super('mgr/permission')
  }

  syncPermissionCodes(codes) {
    return this.post('sync-code', {codes})
  }

  allPermissions(id) {
    return this.get('all').then(data => {
      const map = data.reduce((r, a) => {
        r[a.moduleTitle] = r[a.moduleTitle] || []
        a.checked = false
        r[a.moduleTitle].push(a)
        return r
      }, {})
      return Object.keys(map).map(key => ({
        title: key,
        checked: false,
        permissions: map[key],
        moduleId: map[key][0].moduleId
      })).sort((a, b) => a.moduleId > b.moduleId ? 1 : (a.moduleId < b.moduleId ? -1 : 0))
    }).then(async data => {
      const codeMap = (await roleApi.permissionCodeList(id)).reduce((r, a) => {
        r[a] = true
        return r
      }, {})
      for (const item of data) {
        let checked = true
        item.permissions.forEach(p => {
          if (codeMap[p.permissionCode]) {
            p.checked = true
          } else {
            checked = false
          }
        })
        item.checked = checked
      }
      return data
    })
  }
}

export const permissionApi = new PermissionApi()
